#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void copy_file(FILE *fp1,FILE *fp2){      //拷贝文件 输入两个文件标识符 将第一个文件标识符所指的文件拷贝到第二个、

	char ch = fgetc (fp1);

	while(ch != EOF){
		fputc(ch,fp2);
		ch = fgetc (fp1);
	}

}


char* which_ID(char *ID){            //通过他的id找到所在文件位置
	if(ID[0] == '1'){
		return "../manager/online/";
	}
	else if(ID[0] == '2'){
		return "../service/online/";
	}
	else{
		return "../customer/online/";
	}
	
}

char* str_cat(char *ch1,char *ch2){				//合成字符串
	char *ret = malloc(sizeof(char)*(strlen(ch1)+strlen(ch2)));
	
	strcpy(ret,ch1);

	strcat(ret,ch2);

	return ret;
	
	
}

void find_char_str(FILE *fp1,FILE *fp2,char *ch){      //复制除了需要的字符串的字符
	char buf[16];
	int i = 0;
	while(fgets(buf,sizeof(buf),fp1) != NULL){
		if(strcmp(buf,ch)){
			fputs(buf,fp2);
		}
	}
}

int quit(char *ID){
	
	char *ch1 = which_ID(ID);
	char *ch2 ;
	char ch[16];
	FILE *fp1;
	FILE *fp2;
	
    	ch2 = str_cat(ch1,"onlineList.txt");   	//合成最终路径

	strcpy(ch,ID);
	strcat(ch,"\n");

	fp1 = fopen(str_cat(ch1,"onlineList.txt"),"r");	//打开在线人员列表
	fp2 = fopen("a","w");	//创建一个暂时打文件

	if(fp1 == NULL || fp2 == NULL){
		return 0;
	}
	
	find_char_str(fp1,fp2,ch); 	//将输入的ID去除后存入fp2;

	fclose(fp1);
	fclose(fp2);


	fp1 = fopen(str_cat(ch1,"onlineList.txt"),"w");
	fp2 = fopen("a","r");
	
	if(fp1 == NULL || fp2 == NULL){
		return 0;
	}

	copy_file(fp2,fp1);    	//将fp2拷贝至fp1;

	fclose(fp1);
	fclose(fp2);

	remove("a");	//删除暂存文件
	remove(str_cat(ch1,ID));   //删除代表登录文件夹内的id文件

	free(ch2);

	return 1;
}

